/**
 * @file 部门管理
 * @date 2025/10/27 11:50:18
 * @author lyqjob@yeah.net
 */

import {  useState, useEffect  } from 'react';
import { Table, Tag, Space, Button, Modal, Form, Input, Radio, Col, Row, message, Select } from 'antd';

import { adminApi } from "@/services/admin";
import AuthButton from '@/components/AuthButton';
import dayjs from '@/utils/dayjs.js';

const { TextArea } = Input;

const Department = () => {
    const [form] = Form.useForm();
    const [formValues, setFormValues] = useState();
    const [open, setOpen] = useState(false);
    const [parent, setParent] = useState({});
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true)
    const [managerList, setManagerList] = useState([])
    const [departmentList, setDepartmentList] = useState([])

    const columns = [
        { title: '部门全称', dataIndex: 'name', key: '', width: 200, fixed: 'left' },
        { title: '部门简称', dataIndex: 'short_name', key: '', width: 150 },
        {
            title: '类型', dataIndex: 'type', key: '', width: 100,
            render: (tag) => {
                return (
                    <Tag color={tag === 0 ? 'gold' : 'green'} key={tag}>
                        {tag === 0 ? '组织' : '部门'}
                    </Tag>
                )
            }
        },
        { title: '部门编码', dataIndex: 'code', key: '', width: 150 },
        { title: '部门负责人', dataIndex: 'manager_name', key: '', width: 150 },
        { title: '联系电话', dataIndex: 'phone', key: '', width: 150 },
        { title: '邮箱', dataIndex: 'email', key: '', width: 150 },
        // { title: '地址', dataIndex: 'address', key: '', width: 200 },
        {
            title: '状态', dataIndex: 'status', key: '', width: 100,
            render: (tag) => {
                return (
                    <Tag color={tag === 0 ? 'green' : 'red'} key={tag}>
                        {tag === 0 ? '正常' : '停用'}
                    </Tag>
                )
            }
        },

        {
            title: '创建时间', dataIndex: 'created_at', key: '', width: 200,
            render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
        },
        {
            title: '创建人', dataIndex: 'create_by_name', key: '', width: 200,
        },

        {
            title: '更新时间', dataIndex: 'updated_at', key: '', width: 200,

            render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
        },
        {
            title: '更新人', dataIndex: 'update_by_name', key: '', width: 200,
        },
        // { title: '', dataIndex: 'remark', key: '', width: 200 },
        {
            title: '操作',
            dataIndex: '',
            key: 'options', width: 200, fixed: 'right',
            render: (text, item) => {
                return (
                    <Space >
                        <AuthButton permission={["department:create"]}>
                            <a
                                onClick={() => {

                                    setOpen(true)
                                    setParent(item)
                                    form.setFieldsValue({ parent_id: item.id, type: item.type })
                                    getManagerList(item.id)
                                }}>增加</a>
                        </AuthButton>
                        {
                            item.is_protected === 0 ?
                                <AuthButton permission={["department:update"]}>
                                    <a onClick={() => {
                                        setFormValues(item)

                                        setOpen(true)
                                        form.setFieldsValue(item)
                                        getManagerList(item.id)
                                    }}>编辑</a>
                                </AuthButton>
                                : null}
                        {
                            item.is_protected === 0 ?
                                <AuthButton permission={["department:delete"]}>
                                    <a onClick={() => deleteDepartment(item.id)}>删除</a>
                                </AuthButton>
                                : null}
                    </Space>
                )
            }

        },
    ];



    // 编辑｜添加
    const onCreate = async values => {
        // 编辑时，需要传递id
        if (formValues?.id) {
            values.id = formValues.id;

            const [err, res] = await adminApi.updateDept(values)
            if (err) {
                // message.warning('添加失败')
                // setOpen(false)
            }
            if (res) {
                message.success('更新成功')
                setFormValues()
                setOpen(false)
                getList()
            }
            return
        }

        const [err, res] = await adminApi.createDept(values)
        if (err) {
            // message.error('添加失败')
        }
        if (res) {
            message.success('添加成功')
            setOpen(false)
            getList()
        }

    };

    useEffect(() => {
        getList()
        getDepartmentList()
    }, [])

    // 获取部门列表
    const getDepartmentList = async () => {

        const [err, result] = await adminApi.getAllDepartment();
        if (err) {
            // message.error('获取部门列表失败')
        }
        if (result) {
            setDepartmentList(result.data?.data)
        }
    }

    // 获取管理员列表
    const getManagerList = async (deptId) => {
        const [err, res] = await adminApi.getManagerList({ department_id: deptId })
        if (err) {
            // message.error('获取管理员列表失败')
        }
        if (res) {
            setManagerList(res.data)
        }
    }

    // 获取部门列表树
    const getList = async () => {

        const [err, result] = await adminApi.getDepartmentTree();
        if (err) {
            // 处理获取部门列表失败的情况
        }
        if (result) {
            setLoading(false)
            setData(result.data)
            setParent(result.data[0])
            window.process.done();
        }

    }

    // 切换组织/部门
    const changeRadio = (eve) => {
        const value = eve.target.value;

        form.setFieldsValue({ type: value })
    }

    // 选择上级部门
    const changeParent = (value, option) => {
        form.setFieldsValue({ type: option['data-extra'] })
    }

    // 删除部门
    const deleteDepartment = async (id) => {
        const [err, result] = await adminApi.deleteDepartment(id);
        if (err) {
            // message.error('删除失败')
            return
            // message.error('删除失败:'+ err.message)
        }
        if (result) {
            message.success('删除成功')
            getList()
        }
    }

    // 选择部门负责人
    const deptmentChange = (value) => {
        const manger = managerList.find(item => item.id === value)
        form.setFieldsValue({ email: manger?.email, phone: manger?.phone, address: manger?.address ? manger?.address + '/' + manger?.detail_address : null })
    }


    // 清空部门负责人
    const clearManager = () => {
        form.setFieldsValue({ email: '', phone: '', address: null })
    }

    return (
        <div className="container">
            <AuthButton permission={["department:create"]}>
                <Button onClick={() => {

                    setOpen(true)
                    setParent(data[0])
                    getManagerList(data[0].id)
                }} type="primary" style={{ marginBottom: 16 }}>
                    新增组织/部门
                </Button>
            </AuthButton>

            <Table
                columns={columns}
                loading={loading}
                rowKey={'id'}
                scroll={{ x: 1500 }}
                expandable={
                    {
                        defaultExpandAllRows: true, // 默认展开所有行
                        expandRowByClick: true, // 点击行展开
                    }
                }
                // expandable={{
                //   expandedRowRender: record => <p style={{ margin: 0 }}>{record.description}</p>,
                //   rowExpandable: record => record.name !== 'Not Expandable',
                // }}
                pagination={false}
                dataSource={data}
            />
            <Modal
                open={open}
                title={!formValues?.id ? '添加组织/部门' : '编辑组织/部门'}
                okText="确定"
                cancelText="取消"
                width={800}
                okButtonProps={{ autoFocus: true, htmlType: 'submit' }}
                onCancel={() => setOpen(false)}
                destroyOnHidden
                modalRender={dom => (
                    <Form
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        layout="horizontal"
                        form={form}
                        name="form_in_modal"
                        initialValues={{ type: 0, parent_id: parent?.id }}
                        clearOnDestroy
                        onFinish={values => onCreate(values)}
                        style={{ maxWidth: 800 }}

                    >
                        {dom}
                    </Form>
                )}
            >
                <Row>
                    <Col span={12}>
                        <Form.Item
                            labelCol={{ span: 5 }}
                            wrapperCol={{ span: 19 }}
                            name="parent_id"
                            label="上级部门"
                            rules={[{ required: true, message: '请选择上级部门' }]}
                        >
                            <Select onChange={changeParent} >
                                {
                                    departmentList.length > 0 && departmentList.map(item => (
                                        <Select.Option key={item.id} value={item.id} data-extra={item.type}>{item.name}</Select.Option>
                                    ))
                                }
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            name="type"
                            label="类型"
                            rules={[{ required: true, message: '请选择节点类型' }]}>
                            <Radio.Group onChange={changeRadio} >
                                <Radio value={0}>组织</Radio>
                                <Radio value={1}>部门</Radio>
                            </Radio.Group>
                        </Form.Item>
                    </Col>
                    {/* <Col span={8}>
                        <Form.Item
                            name="code"
                            label="编码"
                        // rules={[{ required: true, message: '请添加节点编码' }]}
                        >
                            <Input placeholder="自动编码" disabled />
                        </Form.Item>
                    </Col> */}

                </Row>
                <Row>
                    <Col span={16}>
                        <Form.Item
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}
                            name="name"
                            label="部门全称"
                            rules={[{ required: true, message: '请添加部门全称' }]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            name="short_name"
                            label="部门简称"
                            rules={[{ required: true, message: '请添加部门简称' }]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>


                </Row>
                <Row>
                    <Col span={8}>
                        <Form.Item
                            // labelCol={{ span: 5 }}
                            name="manager_id"
                            label="部门负责人"
                        >
                            <Select onChange={deptmentChange} allowClear onClear={clearManager}>
                                {
                                    managerList.map(item => (
                                        <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                                    ))
                                }
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item

                            name="phone"
                            label="联系电话"
                        >
                            <Input disabled />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item

                            name="email"
                            label="邮箱"
                        >
                            <Input disabled />
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    {/* <Col span={16}>
                        <Form.Item
                            labelCol={{ span: 2 }}
                            wrapperCol={{ span: 22 }}
                            name="address"
                            label="地址"
                        >
                            <Input disabled />
                        </Form.Item>
                    </Col> */}
                </Row>
                <Row>
                    <Col span={16}>
                        <Form.Item
                            labelCol={{ span: 4 }}
                            name="responsibility"
                            label="部门职责"
                        >
                            <TextArea rows={4} />
                        </Form.Item>
                    </Col>
                    {/* <Col span={12}>
                        <Form.Item
                            labelCol={{ span: 2 }}
                            name="remark"
                            label="备注"
                        >
                            <TextArea rows={4} />
                        </Form.Item>
                    </Col> */}
                </Row>
            </Modal>
        </div>

    )
}

export default Department;